package com.junxonline.plat.dao.repository;

import com.junxonline.plat.dao.model.Menu;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: MenuRepository
 * @Description: 菜单数据操作类
 * @author JunX
 */
@Repository
public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificationExecutor<Menu> {

    Menu findByMenuId(Long menuId);

    Menu findByMenuUrl(String menuUrl);

    @Query(value =
            "SELECT menu.* FROM sys_menu menu " +
            "WHERE menu.menu_type IN (0, 1) ORDER BY menu.menu_sort ASC", nativeQuery = true)
    List<Menu> findAllMenusByMenuTypeIn();

    @Query(value =
            "SELECT menu.* FROM sys_role_menu role_menu " +
            "LEFT JOIN sys_role role ON role.role_id = role_menu.role_id " +
            "LEFT JOIN sys_menu menu ON menu.menu_id = role_menu.menu_id " +
            "WHERE role.role_id = ?1 ORDER BY menu.menu_sort ASC", nativeQuery = true)
    List<Menu> findMenusByRoleIdOrderByMenuSortAsc(Long roleId);

    List<Menu> findByMenuIdIn(Long[] menuIds);

    @Query(value = "SELECT role_menu.* FROM sys_role_menu role_menu WHERE role_menu.menu_id = ?1", nativeQuery = true)
    List<Map<String, BigInteger>> findRoleMenusByMenuId(Long menuId);

    @Modifying
    @Query(value ="DELETE FROM sys_role_menu WHERE menu_id = ?1 AND role_id = ?2", nativeQuery = true)
    void deleteRoleMenuIn(Long menuId, Long roleId);

}
